<template>
  <el-dialog v-loading="loading" v-model="dialogVisible" title="添加价格" width="800">
    <div class="result">
      <el-table :data="tableData" border style="width: 100%" max-height="600">
        <el-table-column type="index" width="50" />
        <el-table-column prop="detail" label="价格">
          <template #default="scope">
          <span
              v-if="!isEditingDetail"
              @dblclick="startEditing(scope.row, 'detail')"
          >
            {{ scope.row.detail }}
          </span>
            <el-input
                v-else
                v-model="scope.row.detail"
                size="small"
                @blur="stopEditing(scope.row, 'detail')"
            />
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作" width="200">
          <template #default="scope">
            <el-tooltip content="双击价格可修改内容" placement="top">
              <el-button
                  size="small"
                  type="primary"
                  @click="onSaveOrUpdate(scope.row)"
              >
                保存
              </el-button>
            </el-tooltip>
            <el-button
                size="small"
                type="primary"
                @click="onDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="pager.currentPage"
          v-model:page-size="pager.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, ->, prev, pager, next, jumper, sizes"
          :total="pager.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <div class="center-aligned-button">
      <el-button type="primary" @click="onAddPrice">新增</el-button>
      <el-button type="primary" @click="onRefresh">刷新</el-button>
      <el-button @click="onCancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, reactive, ref, computed, watch } from "vue";
import {
  selectPricePage, deletePrice, createPrice, updatePrice,
} from "@/network/api";

const requestData = () => {
  loading.value = true;
  selectPricePage({
    labelName: searchForm.labelName,
    goodsId: props.param.id.toString(),
    size: pager.pageSize,
    current: pager.currentPage,
  })
      .then((res) => {
        if (res?.data) {
          pager.total = res.data.total;
          tableData.value = res.data.records || [];
        } else {
          pager.total = 0;
          tableData.value = [];
        }
      })
      .finally(() => {
        loading.value = false;
      });
};
const searchForm = reactive({
  labelName: "",
  goodsId: "",
});
const pager = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const tableData = ref([]);
const onRefresh = () => {
  onSearch();
};

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  param: {
    type: Object,
    default: null,
  },
});
const onSearch = () => {
  pager.currentPage = 1;
  requestData();
};
const loading = ref(false);
const isEditingDetail = ref(false);

const emits = defineEmits(["update:show", "refresh"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(val) {
    emits("update:show", val);
  },
});
const onDelete = (row) => {
  if(!row.id) {
    tableData.value.shift();
    return;
  }
  deletePrice({
    priceId: row.id.toString(),
  }).then((res) => {
    if (res?.code === 200) {
      // 删除成功
      ElMessage({
        message: "delete success",
        type: "success",
      });
      onSearch();
    } else {
      // 删除失败
      ElMessage({
        message: "delete failed",
        type: "error",
      });
    }
  });
};
const onAddPrice = () => {
  tableData.value.unshift({
    detail:"双击修改内容"
  });
};
const onSaveOrUpdate = (row) => {
  if(row.id) {
    updatePrice({
      id: row.id.toString(),
      detail: row.detail,
      goodsId: props.param.id.toString(),
    }).then((res) => {
      onSearch();
    });
  }else{
    createPrice({
      detail: row.detail,
      goodsId: props.param.id.toString(),
    }).then((res) => {
      onSearch();
    });
  }
}
const handleSizeChange = (size) => {
  pager.pageSize = size;
  pager.currentPage = 1;
  requestData();
};
const handleCurrentChange = (cur) => {
  pager.currentPage = cur;
  requestData();
};
watch(dialogVisible, (value) => {
  onSearch();
});
const onCancel = () => {
  emits("update:show", false);
};
const startEditing = (row, fieldName) => {
  isEditingDetail.value = true;
}
const stopEditing = (row, fieldName) => {
  // 停止编辑当前字段
  isEditingDetail.value = false;
};
</script>
<style lang="scss" scoped>
.btn_group {
  text-align: center;
}
.center-aligned-button{
  display:flex;
  justify-content: center;
  align-items: center;
}
</style>
